//
//  RNCommonModule.m
//  RNCommunity
//
//  Created by 朱吉峥 on 2020/2/19.
//  Copyright © 2020 朱吉峥. All rights reserved.
//

#import "RNCommonModule.h"
#import "RNTYYLabel.h"
#import "RNTYYLabelManager.h"

@interface RNCommonModule ()
@property (nonatomic, strong) NSArray *emojiArr;
@property (nonatomic, strong) NSArray *emojiNameArr;
@property (nonatomic, strong) NSMutableDictionary *cacheHeightDict;
@end

@implementation RNCommonModule

RCT_EXPORT_MODULE()

//RCT_REMAP_METHOD(getDeviceType, event:(RCTResponseSenderBlock)callback) {
//    if ([[UIDevice currentDevice] isPad]) {
//        callback(@[[NSNull null], @"iPad"]);
//    } else {
//        callback(@[[NSNull null], @"iPhone"]);
//    }
//}

//RCT_REMAP_METHOD(getDeviceType, resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) {
//    if ([[UIDevice currentDevice] isPad]) {
//        resolve(@"iPad");
//    } else {
//        reject(@"", @"", nil);
//    }
//}
//

#pragma mark - 表情显示
- (NSArray *)emojiArr
{
    if (!_emojiArr) {
        _emojiArr = [RNTYYLabelManager emojiArr];
    }
    return _emojiArr;
}

- (NSArray *)emojiNameArr
{
    if (!_emojiNameArr) {
        _emojiNameArr = [RNTYYLabelManager emojiNameArr];
    }
    return _emojiNameArr;
}

- (NSMutableDictionary *)cacheHeightDict
{
    if (!_cacheHeightDict) {
        _cacheHeightDict = [NSMutableDictionary dictionary];
    }
    return _cacheHeightDict;
}

RCT_REMAP_METHOD(getContentHeight, getContentHeightWithStr:(NSString *)str contentFontSize:(CGFloat)contentFontSize gifFontSize:(CGFloat)gifFontSize preferredMaxLayoutWidth:(CGFloat)preferredMaxLayoutWidth event:(RCTResponseSenderBlock)callback) {
    NSDictionary *dict = @{@"str":str, @"contentFontSize":@(contentFontSize), @"gifFontSize":@(gifFontSize), @"preferredMaxLayoutWidth":@(preferredMaxLayoutWidth)};
    NSNumber *number = [self.cacheHeightDict objectForKey:dict];
    if ([str isEqualToString:@"有没有小姐姐求[舞蹈][舞蹈][拍手][舞蹈][舞蹈][拍手[舞蹈][舞蹈][拍手][舞蹈][舞蹈][拍手安慰"]) {
        NSLog(@"number = %@", number);
    }
    if (number) {
        callback(@[[NSNull null], number]);
        return ;
    }
    PYWeakSelf
    dispatch_async_on_main_queue(^{
        PYStrongSelf
        NSMutableArray *locationArr = [NSMutableArray array];
        NSString *resultStr = [strongSelf handleStr:str locationArr:locationArr];
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:resultStr];
        attri.font = [UIFont systemFontOfSize:contentFontSize];
        [locationArr enumerateObjectsUsingBlock:^(NSArray * arr, NSUInteger idx, BOOL * _Nonnull stop) {
            if (arr.count == 0) {
                if (idx == locationArr.count - 1) {
                    [strongSelf caculateSizeWithPreferredMaxLayoutWidth:preferredMaxLayoutWidth attri:attri callback:callback dict:dict];
                }
                return ;
            }
            NSString *emoji = strongSelf.emojiArr[idx];
            [arr enumerateObjectsUsingBlock:^(NSNumber *location, NSUInteger i, BOOL * _Nonnull stop) {
                [RNTYYLabelManager addOperationWithBlock:^{
                    YYImage *image = [YYImage imageNamed:emoji];
                    dispatch_async_on_main_queue(^{
                        YYAnimatedImageView *gifView = [[YYAnimatedImageView alloc] initWithImage:image];
                        gifView.frame = CGRectMake(0, 0, gifFontSize, gifFontSize);
                        NSMutableAttributedString *attachText = [NSMutableAttributedString attachmentStringWithContent:gifView contentMode:UIViewContentModeScaleAspectFit attachmentSize:gifView.frame.size alignToFont:[UIFont systemFontOfSize:contentFontSize] alignment:YYTextVerticalAlignmentCenter];
                        [attri replaceCharactersInRange:NSMakeRange(location.integerValue, attachText.length) withAttributedString:attachText];
                        if (i == arr.count - 1 && idx == locationArr.count - 1) {
                            [strongSelf caculateSizeWithPreferredMaxLayoutWidth:preferredMaxLayoutWidth attri:attri callback:callback dict:dict];
                        }
                    });
                }];
            }];
        }];
    });
}

- (void)caculateSizeWithPreferredMaxLayoutWidth:(CGFloat)preferredMaxLayoutWidth
                                          attri:(NSAttributedString *)attri
                                       callback:(RCTResponseSenderBlock)callback
                                           dict:(NSDictionary *)dict
{
    //计算文本尺寸
    CGSize maxSize = CGSizeMake(preferredMaxLayoutWidth, MAXFLOAT);
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:attri];
    [self.cacheHeightDict setObject:@(layout.textBoundingSize.height) forKey:dict];
    callback(@[[NSNull null], @(layout.textBoundingSize.height)]);
}

- (NSString *)handleStr:(NSString *)str locationArr:(NSMutableArray *)locationArr
{
    if (![locationArr isKindOfClass:[NSMutableArray class]] || !str) {
        NSLog(@"处理数据异常");
        return nil;
    }
    NSString *resultStr = str;
    for (NSString *emojiName in self.emojiNameArr) {
        NSMutableArray *arr = [NSMutableArray array];
        resultStr = [self handleStr:resultStr emojiName:emojiName arr:arr];
        [locationArr addObject:arr];
    }
    return resultStr;
}

- (NSString *)handleStr:(NSString *)str emojiName:(NSString *)emojiName arr:(NSMutableArray *)arr
{
    if (![arr isKindOfClass:[NSMutableArray class]] || !emojiName || !str) {
        NSLog(@"处理数据异常");
        return nil;
    }
    NSString *resultStr = str;
    NSRange range = [str rangeOfString:emojiName];
    NSMutableString *replaceStr = [NSMutableString string];
    for (int i = 0; i < emojiName.length; i++) {
        [replaceStr appendString:@"\0"];
    }
    if (range.location != NSNotFound) {
        [arr addObject:@(range.location)];
        resultStr = [str stringByReplacingCharactersInRange:range withString:replaceStr];
        return [self handleStr:resultStr emojiName:emojiName arr:arr];
    }
    return resultStr;
}


@end
